<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MutationObserver demo</title>
</head>
<body>
    <div id="info" style="color:brown; font-size: 20px;">正在监听#wrap</div>
    <div id="wrap"></div>
    <script>
        var body = document.body;
        var info = document.getElementById('info');

        main();

        // 创建MutationObserver对象及其回调
        function createMutationObserverObject(){
            var MutationObserver = window.MutationObserver ||
            window.WebKitMutationObserver ||
            window.MozMutationObserver;

            if(!MutationObserver){
                info.innerHTML = '您的浏览器不支持MutationObserver对象!';
                return false;
            }
            return new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    info.innerHTML = '监听到DOM变化，新增元素的id: ' + mutation.addedNodes[0].id;
                });    
            });
        }

        // 使用MutationObserver对象的observe方法对目标节点监听
        function listen(){
            var observer = createMutationObserverObject();
            if(!observer) return;
            observer.observe(wrap, { attributes: true, childList: true});
        }

        // 定时往目标节点新增元素查看监听情况
        function main(){
            listen();
            var count = 0;
            var listenDom = setInterval(function(){
                count++;
                var p = document.createElement('p');
                p.id = 'p' + count;
                p.innerText = "我的id是 p" + count;
                wrap.appendChild(p);
                if(count>=5){
                    clearInterval(listenDom);
                    //observer.disconnect();
                }
            }, 1500)
        }
    </script>
</body>
</html>